"""
:mod:`pynchon.bio.data.dirichlet`
=================================

Dirichlet mixture models.
"""
import os
import numpy as np
DIRICHLET_PATH = os.path.join(os.path.dirname(__file__), 'dirichlet')

def parse_comp(fh):
    line = fh.readline()
    if not line.startswith('ClassName'):
        raise ValueError('The file %s does not contain a valid Dirichlet mixture.' \
                         % fh.name)
    weights = []
    alphas = []
    while line:
        if line.startswith('Name'):
            name = line.split()[2].replace('.','_').replace('-','_')
        elif line.startswith('Order'):
            symbols = line.split()[2:]
        elif line.startswith('Mixture'):
            weight = float(line.split()[1])
            weights.append(weight)
            alpha = [float(a) for a in fh.readline().split()[2:]] # the first is the sum
            alphas.append(alpha)
            # comment = fh.readline()[9:-1]
            # comments.append(comment) 
        line = fh.readline()
    return (name, (tuple(symbols), np.array(weights), np.array(alphas)))
    

for fn in os.listdir(DIRICHLET_PATH):
    fh = open(os.path.join(DIRICHLET_PATH, fn), 'rb')
    if fn.endswith('comp'):
        name, data = parse_comp(fh)
        globals()[name] = data
    else:
        fh.close()
        continue
    
